package com.jeesite.modules.web;

import com.jeesite.modules.common.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 文件上传控制器
 * 处理头像等文件上传功能
 */
@RestController
@RequestMapping("/file")
public class FileController {

    private static final Logger logger = LoggerFactory.getLogger(FileController.class);

    @Value("${file.upload-path:/userfiles/upload/}")
    private String uploadPath;

    @Value("${server.servlet.context-path:}")
    private String contextPath;

    /**
     * 上传头像
     */
    @PostMapping("/upload-avatar")
    public Result<Map<String, Object>> uploadAvatar(@RequestParam("file") MultipartFile file) {
        try {
            // 参数校验
            if (file.isEmpty()) {
                return Result.fail("请选择要上传的文件");
            }

            // 检查文件类型
            String contentType = file.getContentType();
            if (contentType == null || !contentType.startsWith("image/")) {
                return Result.fail("只能上传图片文件");
            }

            // 检查文件大小（限制为10MB）
            if (file.getSize() > 10 * 1024 * 1024) {
                return Result.fail("文件大小不能超过10MB");
            }

            // 获取文件扩展名
            String originalFilename = file.getOriginalFilename();
            String extension = "";
            if (originalFilename != null && originalFilename.contains(".")) {
                extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            }

            // 生成新的文件名
            String fileName = UUID.randomUUID().toString() + extension;

            // 创建上传目录
            String avatarDir = uploadPath + "avatars/";
            Path uploadDir = Paths.get(avatarDir);
            if (!Files.exists(uploadDir)) {
                Files.createDirectories(uploadDir);
            }

            // 保存文件
            Path filePath = uploadDir.resolve(fileName);
            Files.copy(file.getInputStream(), filePath);

            // 生成访问URL
            String fileUrl = contextPath + "/userfiles/upload/avatars/" + fileName;

            Map<String, Object> result = new HashMap<>();
            result.put("url", fileUrl);
            result.put("fileName", fileName);
            result.put("originalName", originalFilename);
            result.put("size", file.getSize());

            logger.info("头像上传成功: {}", fileName);
            return Result.success("上传成功", result);

        } catch (IOException e) {
            logger.error("头像上传失败", e);
            return Result.fail("上传失败: " + e.getMessage());
        } catch (Exception e) {
            logger.error("头像上传异常", e);
            return Result.fail("上传异常: " + e.getMessage());
        }
    }

    /**
     * 通用文件上传
     */
    @PostMapping("/upload")
    public Result<Map<String, Object>> uploadFile(@RequestParam("file") MultipartFile file) {
        try {
            // 参数校验
            if (file.isEmpty()) {
                return Result.fail("请选择要上传的文件");
            }

            // 检查文件大小（限制为10MB）
            if (file.getSize() > 10 * 1024 * 1024) {
                return Result.fail("文件大小不能超过10MB");
            }

            // 获取文件扩展名
            String originalFilename = file.getOriginalFilename();
            String extension = "";
            if (originalFilename.contains(".")) {
                extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            }

            // 生成新的文件名
            String fileName = UUID.randomUUID().toString() + extension;

            // 创建上传目录
            String fileDir = uploadPath + "files/";
            Path uploadDir = Paths.get(fileDir);
            if (!Files.exists(uploadDir)) {
                Files.createDirectories(uploadDir);
            }
            System.out.println(uploadDir);

            // 保存文件
            Path filePath = uploadDir.resolve(fileName);
            System.out.println(filePath);
            Files.copy(file.getInputStream(), filePath);

            // 生成访问URL
            String fileUrl = contextPath + "/userfiles/upload/files/" + fileName;

            Map<String, Object> result = new HashMap<>();
            result.put("url", fileUrl);
            result.put("fileName", fileName);
            result.put("originalName", originalFilename);
            result.put("size", file.getSize());
            result.put("contentType", file.getContentType());

            logger.info("文件上传成功: {}", fileName);
            return Result.success("上传成功", result);

        } catch (IOException e) {
            logger.error("文件上传失败", e);
            return Result.fail("上传失败: " + e.getMessage());
        } catch (Exception e) {
            logger.error("文件上传异常", e);
            return Result.fail("上传异常: " + e.getMessage());
        }
    }
}
